<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图书管理系统</title>
    <!-- 引入bootstrap.css -->
    <link
      rel="stylesheet"
      href="../../lib/bootstrap/dist/css/bootstrap.min.css"
    />
    <!-- 公共 -->
    <link rel="stylesheet" href="../../css/base.css" />
    <link rel="stylesheet" href="./index.css" />
  </head>

  <body>
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
      <div class="container-fluid">
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNavAltMarkup"
          aria-controls="navbarNavAltMarkup"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav">
            <a class="nav-link" href="../main">首页</a>
            <a class="nav-link" href="../search">搜索</a>
            <a class="nav-link" href="../borrow">借阅</a>
            <a class="nav-link" href="../people">个人</a>
            <a class="nav-link" href="../detail">图书详情</a>
            <a class="nav-link" href="../login">退出</a>
          </div>
        </div>
      </div>
    </nav>

    <!-- 提示框 -->
    <div class="alert info-box">操作结果</div>
    <!-- 借阅记录 -->
    <div class="big">
      <h2 class="mt-4">借阅记录</h2>
      <table class="table table-striped mt-3">
        <thead>
          <tr>
            <th scope="col">借阅记录ID</th>
            <th scope="col">用户ID</th>
            <th scope="col">图书ID</th>
            <th scope="col">借阅日期</th>
            <th scope="col">最晚归还日期</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody class="tb">
          <!-- 动态渲染 -->
        </tbody>
      </table>
    </div>
  </body>
  <script src="../../lib/axios/dist/axios.min.js"></script>
  <script src="../../utils/alert.js"></script>
  <script src="../../utils/request.js"></script>
  <script>
    // 借阅记录页面渲染
    async function render() {
      const res = await axios("/record/library/borrow_records/page", {
        // 时间来不及做分页了，只能默认设置,条数不多的时候显示也还行
        params: {
          page: 1,
          pageSize: 100,
        },
      });
      records = res.data.data.records;
      for (let i = records.length - 1; i > 0; i--) {
        // console.log(i, records[i])
        // 由于借阅记录的接口后端返回的是整个表内的记录，没有对不同的用户进行区分，所以需要在前端进行区分
        // 如果不是登录用户的借阅记录，不显示
        // 如果写管理员后台页面，可以显示所有借阅记录
        const userId = localStorage.getItem("userId");
        if (records[i].userId == userId) {
          if (records.length === 0) {
            // 无借阅记录，不需要进行下面的操作
            return;
          }
          // 生成一个当前的时间戳，借阅成功后归还日期为当前时间，判断显示的内容
          let timestamp = +new Date();
          let date = new Date(timestamp);
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, "0");
          let day = String(date.getDate()).padStart(2, "0");
          let formattedDate = `${year}-${month}-${day}`;
          //  console.log(formattedDate);
          document.querySelector(".tb").innerHTML += `
          <tr>
          <td>${records[i].recordId}</td>
          <td>${records[i].userId}</td>
          
          <td>${records[i].bookId}</td>
   
          <td>${records[i].borrowDate}</td>
          <td>${
            records[i].returnDate === null ||
            records[i].returnDate === formattedDate
              ? "已归还"
              : records[i].returnDate
          }</td>
          <td>
            ${
              records[i].returnDate !== null &&
              records[i].returnDate !== formattedDate
                ? `<button class="btn btn-primary btn-sm return-button" data-book-id="${records[i].bookId}" data-record-id="${records[i].recordId}" data-borrow-date="${records[i].borrowDate}">归还</button>`
                : `<button class="btn btn-success btn-sm" disabled>已归还</button> `
            }
            <button class="btn btn-secondary btn-sm look" data-book-id="${
              records[i].bookId
            }">查看</button>                         
          </td>
        </tr>
      `;
        }
      }

      // 检查表格是否没有任何行
      if (document.querySelector(".tb").children.length === 0) {
        document.querySelector(".tb").innerHTML = `
            <tr>
                <td colspan="6" style="text-align: center;">暂无借阅记录</td>
            </tr>
        `;
      }
      // 获取所有查看按钮并添加事件监听

      const lookButtons = document.querySelectorAll(".look");
      // console.log(lookButtons.length); // 检查按钮数量

      lookButtons.forEach((button) => {
        button.addEventListener("click", (e) => {
          // 阻止默认行为
          e.preventDefault();
          // 获取当前书名
          const bookId = e.target.dataset.bookId;
          // 将数据存储到localStorage
          localStorage.setItem("bookId", bookId);
          // 跳转到目标页面
          location.href = "../detail";
        });
      });
      //  获取所有查看按钮并添加事件监听
      document.querySelectorAll(".return-button").forEach((button) => {
        button.addEventListener("click", async (e) => {
          /**
           * 由于书籍归还状态的时候后端传过来的最晚归还日期是当天日期，
           * 我们想判断是否已经归还就可以通过判断最晚归还日期是否是当天日期，
           * 点击归还按钮后如果原先没归还变成归还，最晚日期就会变成已归还，归还按钮改成已归还
           */

          let timestamp = +new Date();
          let date = new Date(timestamp);
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, "0");
          let day = String(date.getDate()).padStart(2, "0");
          let formattedDate = `${year}-${month}-${day}`;
          //  console.log(formattedDate);
          // 从本地存储获取用户id
          const bookId = e.target.getAttribute("data-book-id"); // 获取图书 ID
          // 将bookid传到本地存储，跳转到detail页面使用
          const recordId = e.target.getAttribute("data-record-id"); // 获取借阅记录 ID
          const res = await axios.put(
            `/book/library/return?record_id=${recordId}`
          );
          // console.log(res.data);
          // console.log(11);
          if (res.data.code === 0) {
            myAlert(false, "归还失败");
            return;
          } else if (res.data.code === 1) {
            myAlert(true, "归还成功");
          }

          // 刷新页面
          document.querySelector(".tb").innerHTML = "";
          render();
        });
      });
    }
    render();
  </script>
</html>
